package com.p7.notepad.tools;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;

import com.p7.notepad.app.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PhotoUtils {

    private Object mWith;

    public static final int SELECT_FROM_CAMERA = 0x0011;
    public static final int SELECT_FROM_PHOTO = 0x0012;

    private OnPhotoListener mListener;

    public PhotoUtils() {
    }

    public PhotoUtils setWith(Object mWith) {
        this.mWith = mWith;
        return this;
    }

    public PhotoUtils setListener(OnPhotoListener mListener) {
        this.mListener = mListener;
        return this;
    }

    private Uri pathUri;
    private File pathFile;
    public void onCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String path = Environment.getExternalStorageDirectory().getPath();
        String name = FileUtils.getPhotoName();
        pathFile = new File(path, name);
        if (Build.VERSION.SDK_INT < 24) {
            pathUri = Uri.fromFile(pathFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, pathUri);
            if (mWith instanceof Activity) {
                ((Activity)mWith).startActivityForResult(intent, SELECT_FROM_CAMERA);
            }
            if (mWith instanceof Fragment) {
                ((Fragment)mWith).startActivityForResult(intent, SELECT_FROM_CAMERA);
            }
        } else {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, pathFile.getAbsolutePath());
            if (mWith instanceof Activity) {
                pathUri = ((Activity)mWith).getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, pathUri);
                ((Activity)mWith).startActivityForResult(intent, SELECT_FROM_CAMERA);
            }
            if (mWith instanceof Fragment) {
                pathUri = ((Fragment)mWith).getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, pathUri);
                ((Fragment)mWith).startActivityForResult(intent, SELECT_FROM_CAMERA);
            }
        }
    }

    public void onPhoto() {
        Intent intent;
//        当sdk版本低于19时使用此方法
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        if (mWith instanceof Activity) {
            ((Activity)mWith).startActivityForResult(intent, SELECT_FROM_PHOTO);
        }
        if (mWith instanceof Fragment) {
            ((Fragment)mWith).startActivityForResult(intent, SELECT_FROM_PHOTO);
        }
    }

    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK ) {
            switch (requestCode) {
                case SELECT_FROM_CAMERA:
                    saveCamera(activity);
                    break;
                case SELECT_FROM_PHOTO:
                    if (data == null) {
                        if (mListener != null) {
                            mListener.onPhotoError("未找到图片");
                        }
                        return;
                    }
//                    String path = GetPathFromUri.getPath(activity, data.getData());
                    onCompress(activity,  GetPathFromUri.getPath(activity, data.getData()));
                    break;
                default:
                    break;
            }
        } else {
            if (mListener != null) {
                mListener.onPhotoError("放弃选取");
            }
        }
    }

    private void saveCamera(Activity activity) {
        if (fileIsExists(pathFile.getPath())) {
            onCompress(activity, pathFile.getPath());
        } else {
            if (mListener != null) {
                mListener.onPhotoError("拍照失败");
            }
        }
    }

    private void onCompress(Context context, String path) {
        if (!fileIsExists(path)) {
            if (mListener != null) {
                mListener.onPhotoError("没有找到SD卡");
            }
            return;
        }

        Luban.with(context)
                .load(new File(path))
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        if (mListener != null) {
                            mListener.onPhotoStart();
                        }
                    }

                    @Override
                    public void onSuccess(File file) {
                        if (mListener != null) {
                            mListener.onPhotoPath(file.getAbsolutePath());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (mListener != null) {
                            mListener.onPhotoError("压缩失败," + e.getMessage());
                        }
                    }
                }).launch();
    }

    public static boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public interface OnPhotoListener {
        void onPhotoStart();
        void onPhotoPath(String imagePath);
        void onPhotoError(String error);
    }
}
